﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using RTUDataAcquisition.Model;
using RTUDataAcquisition.AppCode;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using Newtonsoft.Json;

namespace RTUDataAcquisition.DataAccess
{
    public class ParseData
    {
        /// <summary>
        /// 解析遥测站加报报
        /// </summary>
        /// <param name="connId">客户端连接ID</param>
        /// <param name="byteData">数据</param>
        /// <returns>true,false</returns>
        public static bool ParseSL651AddReport(IntPtr connId, byte[] byteData)
        {
            try
            {
                int intLength = 0;//报文正文数据长度
                int serial = 0;//流水号
                string strTime1;// 发报时间
                string strAddrNo;//遥测站地址标识符
                string strAddr; //遥测站地址
                                //string strAddrType;//遥测站类型
                string strTime2; //观测时间
                byte[] byteEssData1;//要素头数据
                byte[] byteEssData2;//要素数据

                intLength = TransData.ConvertNum(byteData[11], byteData[12]);
                byteEssData1 = new byte[intLength];
                Array.Copy(byteData, MainForm.Rtu_header_size, byteEssData1, 0, intLength);

                byte[] byteSerial = new byte[2];
                Array.Copy(byteEssData1, 0, byteSerial, 0, 2);
                serial = TransData.ConvertNum(byteSerial[0], byteSerial[1]);

                byte[] time1 = new byte[6];
                Array.Copy(byteEssData1, 2, time1, 0, 6);
                strTime1 = TransData.DataToDateString(time1);

                byte[] add = new byte[2];
                Array.Copy(byteEssData1, 8, add, 0, 2);
                strAddrNo = TransData.ConvertData(add);

                byte[] addr = new byte[5];
                Array.Copy(byteEssData1, 10, addr, 0, 5);
                strAddr = TransData.ConvertData(addr);

                byte[] addrType = new byte[1];//遥测站类型
                Array.Copy(byteEssData1, 15, addrType, 0, 1);
                //strAddrType = TransData.ConvertData(addrType);

                byte[] time2 = new byte[5];
                Array.Copy(byteEssData1, 18, time2, 0, 5);
                strTime2 = TransData.DataToDateString(time2);

                byteEssData2 = new byte[intLength - 23];
                Array.Copy(byteEssData1, 23, byteEssData2, 0, intLength - 23);

                List<EssDataModel> listModel = new List<EssDataModel>();
                List<byte> listEssData = byteEssData2.ToList<byte>();
                EssDataModel essDataModel = new EssDataModel();
                essDataModel.ST = strAddr;
                //strTime2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm") +":00";//测试用，正式用要注释掉
                essDataModel.TT = Convert.ToDateTime(strTime2).ToString("yyyy-MM-dd HH:mm:ss.fff");
                essDataModel.TYPE = "OVERTIME";
                essDataModel.SERIAL = serial;
                essDataModel.TELTYPE = Convert.ToInt16(addrType[0]);
                essDataModel.STT = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                essDataModel.UT = Convert.ToDateTime(strTime1).ToString("yyyy-MM-dd HH:mm:ss.fff");
                int i = MainForm.TransDeviceInfo.Select("ST='" + strAddr + "'").Length;
                //Messages.SaveLog("是否存在转发ST=" + strAddr+ ";i="+ i.ToString());
                DataBusiness.CreateHisDataTable(strAddr, INIConfig.GetDBConnectionString());
               if(i >= 1)
                {
                    DataBusiness.CreateHisDataTable(strAddr, INIConfig.GetRDBConnectionString());
                }
                if (!DataBusiness.CheckData(essDataModel.ST, essDataModel.TT, essDataModel.TYPE, essDataModel.SERIAL))
                {
                    if (ParseEssData(listEssData, essDataModel, ref listModel))
                    {
                        DataBusiness.DeleteRealData(strAddr);
                        if (i >= 1)
                        {
                            DataBusiness.DeleteRealData_R(strAddr);
                        }
                        if (DataBusiness.InsertRealAndHisData(listModel, strAddr,i))
                        {
                            DataBusiness.InsertStationConfig(essDataModel);
                            if (i >= 1)
                            {
                                DataBusiness.InsertStationConfig_R(essDataModel);
                            }
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    //Messages.SaveLog(string.Format("遥测站{0}[{1}]数据重复", essDataModel.ST, essDataModel.TT), ELogLayer.UI, ELogType.Info);
                    return true;
                }

                //var obj = MainForm.server.GetExtra<ClientModel>(connId);
                //if (obj != null)//判断当前链接是否存在
                //{
                //    List<byte> listSend = new List<byte>();
                //    listSend.Add(0x7E);
                //    listSend.Add(0x7E);
                //    listSend.AddRange(addr);
                //    listSend.Add(byteData[2]);
                //    listSend.Add(byteData[8]);
                //    listSend.Add(byteData[9]);
                //    listSend.Add(byteData[10]);
                //    listSend.Add(0x80);
                //    listSend.Add(0x08);
                //    listSend.Add(0x02);
                //    listSend.AddRange(byteSerial);
                //    listSend.AddRange(TransData.ConvertHexStringToBytes(DateTime.Now.ToString("yyyyMMddHHmmss").Substring(2)));
                //    listSend.Add(0x04);
                //    int crc = TransData.CRC16(listSend.ToArray(), listSend.Count);   //对数据进行CRC校验
                //    listSend.Add((byte)(crc >> 8));
                //    listSend.Add((byte)(crc >> 0));
                //    MainForm.server.Send(connId, listSend.ToArray(), listSend.Count);
                //}
                //return true;
            }
            catch (Exception ex)
            {
                Messages.SaveLog(string.Format("解析遥测站加报报异常:{0} 数据内容:{1}", ex.Message, TransData.ConvertData(byteData)), ELogLayer.UI, ELogType.Info);
                return false;
            }
        }

        /// <summary>
        /// 解析遥测站小时报
        /// </summary>
        /// <param name="connId">客户端连接ID</param>
        /// <param name="byteData">数据</param>
        /// <returns>true,false</returns>
        public static bool ParseSL651HoursReport(IntPtr connId, byte[] byteData)
        {
            try
            {
                int intLength = 0;//报文正文数据长度
                int serial = 0;//流水号
                string strTime1;// 发报时间
                string strAddrNo;//遥测站地址标识符
                string strAddr; //遥测站地址
                                //string strAddrType;//遥测站类型
                string strTime2; //观测时间
                byte[] byteEssData1;//要素头数据
                byte[] byteEssData2;//要素数据

                intLength = TransData.ConvertNum(byteData[11], byteData[12]);
                byteEssData1 = new byte[intLength];
                Array.Copy(byteData, MainForm.Rtu_header_size, byteEssData1, 0, intLength);

                byte[] byteSerial = new byte[2];
                Array.Copy(byteEssData1, 0, byteSerial, 0, 2);
                serial = TransData.ConvertNum(byteSerial[0], byteSerial[1]);

                byte[] time1 = new byte[6];
                Array.Copy(byteEssData1, 2, time1, 0, 6);
                strTime1 = TransData.DataToDateString(time1);

                byte[] add = new byte[2];
                Array.Copy(byteEssData1, 8, add, 0, 2);
                strAddrNo = TransData.ConvertData(add);

                byte[] addr = new byte[5];
                Array.Copy(byteEssData1, 10, addr, 0, 5);
                strAddr = TransData.ConvertData(addr);

                byte[] addrType = new byte[1];//遥测站类型
                Array.Copy(byteEssData1, 15, addrType, 0, 1);
                //strAddrType = TransData.ConvertData(addrType);

                byte[] time2 = new byte[5];
                Array.Copy(byteEssData1, 18, time2, 0, 5);
                strTime2 = TransData.DataToDateString(time2);

                byteEssData2 = new byte[intLength - 23];
                Array.Copy(byteEssData1, 23, byteEssData2, 0, intLength - 23);

                //List<EssDataModel> listModel = new List<EssDataModel>();
                //List<byte> listEssData = byteEssData2.ToList<byte>();
                //EssDataModel essDataModel = new EssDataModel();
                //essDataModel.ST = strAddr;
                ////strTime2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm") +":00";//测试用，正式用要注释掉
                //essDataModel.TT = Convert.ToDateTime(strTime2).ToString("yyyy-MM-dd HH:mm:ss.fff");
                //essDataModel.TYPE = "OVERTIME";
                //essDataModel.SERIAL = serial;
                //essDataModel.TELTYPE = Convert.ToInt16(addrType[0]);
                //essDataModel.STT = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                //essDataModel.UT = Convert.ToDateTime(strTime1).ToString("yyyy-MM-dd HH:mm:ss.fff");
                //DataBusiness.CreateHisDataTable(strAddr, INIConfig.GetDBConnectionString());

                //if (!DataBusiness.CheckData(essDataModel.ST, essDataModel.TT, essDataModel.TYPE, essDataModel.SERIAL))
                //{
                //    if (ParseEssData(listEssData, essDataModel, ref listModel))
                //    {
                //        DataBusiness.DeleteRealData(strAddr);
                //        DataBusiness.InserRealAndHisData(listModel, strAddr);
                //        DataBusiness.InsertStationConfig(essDataModel);
                //        //DataBusiness.InsertStationStatus(strAddr, listModel);
                //        //AddEssData(strAddr, listModel);
                //    }
                //}
                //else
                //{
                //    Messages.SaveLog(string.Format("遥测站{0}[{1}]数据重复", essDataModel.ST, essDataModel.TT), ELogLayer.UI, ELogType.Info);
                //}

                //var obj = MainForm.server.GetExtra<ClientModel>(connId);
                //if (obj != null)//判断当前链接是否存在
                //{
                //    List<byte> listSend = new List<byte>();
                //    listSend.Add(0x7E);
                //    listSend.Add(0x7E);
                //    listSend.AddRange(addr);
                //    listSend.Add(byteData[2]);
                //    listSend.Add(byteData[8]);
                //    listSend.Add(byteData[9]);
                //    listSend.Add(byteData[10]);
                //    listSend.Add(0x80);
                //    listSend.Add(0x08);
                //    listSend.Add(0x02);
                //    listSend.AddRange(byteSerial);
                //    listSend.AddRange(TransData.ConvertHexStringToBytes(DateTime.Now.ToString("yyyyMMddHHmmss").Substring(2)));
                //    listSend.Add(0x04);
                //    int crc = TransData.CRC16(listSend.ToArray(), listSend.Count);   //对数据进行CRC校验
                //    listSend.Add((byte)(crc >> 8));
                //    listSend.Add((byte)(crc >> 0));
                //    MainForm.server.Send(connId, listSend.ToArray(), listSend.Count);
                //}
                return true;
            }
            catch (Exception ex)
            {
                Messages.SaveLog(string.Format("解析遥测站加报报异常:{0},数据内容:{1}", ex.Message, TransData.ConvertData(byteData)), ELogLayer.UI, ELogType.Info);
                return false;
            }
        }

        /// <summary>
        /// 解析均匀时段水文信息报
        /// </summary>
        /// <param name="connId">客户端连接ID</param>
        /// <param name="byteData">数据</param>
        /// <returns>true,false</returns>
        public static bool ParseSL651IntervalReport(IntPtr connId, byte[] byteData)
        {
            try
            {
                int intLength = 0;//报文正文数据长度
                int serial = 0;//流水号
                string strTime1;// 发报时间
                string strAddrNo;//遥测站地址标识符
                string strAddr; //遥测站地址
                                //string strAddrType;//遥测站类型
                string strTime2; //观测时间
                byte[] byteEssData1;//要素头数据
                byte[] byteEssData2;//要素数据

                intLength = TransData.ConvertNum(byteData[11], byteData[12]);
                byteEssData1 = new byte[intLength];
                Array.Copy(byteData, MainForm.Rtu_header_size, byteEssData1, 0, intLength);

                byte[] byteSerial = new byte[2];
                Array.Copy(byteEssData1, 0, byteSerial, 0, 2);
                serial = TransData.ConvertNum(byteSerial[0], byteSerial[1]);

                byte[] time1 = new byte[6];
                Array.Copy(byteEssData1, 2, time1, 0, 6);
                strTime1 = TransData.DataToDateString(time1);

                byte[] add = new byte[2];
                Array.Copy(byteEssData1, 8, add, 0, 2);
                strAddrNo = TransData.ConvertData(add);

                byte[] addr = new byte[5];
                Array.Copy(byteEssData1, 10, addr, 0, 5);
                strAddr = TransData.ConvertData(addr);

                byte[] addrType = new byte[1];//遥测站类型
                Array.Copy(byteEssData1, 15, addrType, 0, 1);
                //strAddrType = TransData.ConvertData(addrType);

                byte[] time2 = new byte[5];
                Array.Copy(byteEssData1, 18, time2, 0, 5);
                strTime2 = TransData.DataToDateString(time2);

                byteEssData2 = new byte[intLength - 23];
                Array.Copy(byteEssData1, 23, byteEssData2, 0, intLength - 23);

                //List<EssDataModel> listModel = new List<EssDataModel>();
                //List<byte> listEssData = byteEssData2.ToList<byte>();
                //EssDataModel essDataModel = new EssDataModel();
                //essDataModel.ST = strAddr;
                ////strTime2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm") +":00";//测试用，正式用要注释掉
                //essDataModel.TT = Convert.ToDateTime(strTime2).ToString("yyyy-MM-dd HH:mm:ss.fff");
                //essDataModel.TYPE = "OVERTIME";
                //essDataModel.SERIAL = serial;
                //essDataModel.TELTYPE = Convert.ToInt16(addrType[0]);
                //essDataModel.STT = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                //essDataModel.UT = Convert.ToDateTime(strTime1).ToString("yyyy-MM-dd HH:mm:ss.fff");
                //DataBusiness.CreateHisDataTable(strAddr, INIConfig.GetDBConnectionString());

                //if (!DataBusiness.CheckData(essDataModel.ST, essDataModel.TT, essDataModel.TYPE, essDataModel.SERIAL))
                //{
                //    if (ParseEssData(listEssData, essDataModel, ref listModel))
                //    {
                //        DataBusiness.DeleteRealData(strAddr);
                //        DataBusiness.InserRealAndHisData(listModel, strAddr);
                //        DataBusiness.InsertStationConfig(essDataModel);
                //        //DataBusiness.InsertStationStatus(strAddr, listModel);
                //        //AddEssData(strAddr, listModel);
                //    }
                //}
                //else
                //{
                //    Messages.SaveLog(string.Format("遥测站{0}[{1}]数据重复", essDataModel.ST, essDataModel.TT), ELogLayer.UI, ELogType.Info);
                //}

                //var obj = MainForm.server.GetExtra<ClientModel>(connId);
                //if (obj != null)//判断当前链接是否存在
                //{
                //    List<byte> listSend = new List<byte>();
                //    listSend.Add(0x7E);
                //    listSend.Add(0x7E);
                //    listSend.AddRange(addr);
                //    listSend.Add(byteData[2]);
                //    listSend.Add(byteData[8]);
                //    listSend.Add(byteData[9]);
                //    listSend.Add(byteData[10]);
                //    listSend.Add(0x80);
                //    listSend.Add(0x08);
                //    listSend.Add(0x02);
                //    listSend.AddRange(byteSerial);
                //    listSend.AddRange(TransData.ConvertHexStringToBytes(DateTime.Now.ToString("yyyyMMddHHmmss").Substring(2)));
                //    listSend.Add(0x04);
                //    int crc = TransData.CRC16(listSend.ToArray(), listSend.Count);   //对数据进行CRC校验
                //    listSend.Add((byte)(crc >> 8));
                //    listSend.Add((byte)(crc >> 0));
                //    MainForm.server.Send(connId, listSend.ToArray(), listSend.Count);
                //}
                return true;
            }
            catch (Exception ex)
            {
                Messages.SaveLog(string.Format("解析遥测站加报报异常:{0},数据内容:{1}", ex.Message, TransData.ConvertData(byteData)), ELogLayer.UI, ELogType.Info);
                return false;
            }
        }



        /// <summary>
        /// 解析要素数据
        /// </summary>
        /// <param name="listEssData">要素数据</param>
        /// <param name="essDataModel">要素数据MODEL</param>
        /// <returns>true，false</returns>
        public static bool ParseEssData(List<byte> listEssData, EssDataModel essDataModel, ref List<EssDataModel> listModel)
        {
            try
            {
                if (listEssData.Count == 0)
                {
                    return true;
                }

                string strEssCode = TransData.ByteToStringH(listEssData[0]);
                List<EssModel> essModel = MainForm.listEss.Where<EssModel>(x => x.EssCode == strEssCode).ToList<EssModel>();
                if (essModel.Count > 0)
                {
                    int intEssLength = TransData.GetEssDataLength(listEssData[1]);
                    int intEssPointLength = TransData.GetEssDataPointLength(listEssData[1]);
                    if (listEssData.Count > intEssLength)
                    {
                        byte[] byteValue = new byte[intEssLength];
                        listEssData.CopyTo(2, byteValue, 0, intEssLength);
                        double? dblValue;
                        if (byteValue[0] == 0xFF)//是否为负数
                        {
                            byte[] byteTemp = new byte[intEssLength - 1];
                            listEssData.CopyTo(3, byteTemp, 0, byteTemp.Length);
                            dblValue = TransData.ConvertData(byteTemp, intEssPointLength);
                            dblValue = 0 - dblValue;
                        }
                        else
                        {
                            dblValue = TransData.ConvertData(byteValue, intEssPointLength);
                        }

                        if (dblValue != null)
                        {
                            if (essModel[0].EssMinValue != 0 && essModel[0].EssMaxValue != 0)
                            {
                                if (dblValue < essModel[0].EssMinValue || dblValue > essModel[0].EssMaxValue)
                                {
                                    dblValue = null;
                                }
                            }
                        }

                        EssDataModel tempModel = new EssDataModel();
                        tempModel.ST = essDataModel.ST;
                        tempModel.TT = essDataModel.TT;
                        tempModel.TYPE = essDataModel.TYPE;
                        tempModel.SERIAL = essDataModel.SERIAL;
                        tempModel.TELTYPE = essDataModel.TELTYPE;
                        tempModel.STT = essDataModel.STT;
                        tempModel.UT = essDataModel.UT;
                        tempModel.SDATA = dblValue == null ? "-" : dblValue.ToString();
                        tempModel.DATA = dblValue == null ? 0 : dblValue;
                        tempModel.ESSName = essModel[0].EssName;
                        tempModel.ESS = essModel[0].EssAscllCode;
                        if (essModel[0].EssCode == "09H")//闸门开启高度
                        {
                            EssDataModel model = listModel.Find(x => x.ESS == "GN");
                            if (model != null)
                            {
                                string strIndex = model.DATA == null ? "" : Convert.ToString(model.DATA + 1);
                                tempModel.ESS = essModel[0].EssAscllCode + strIndex;
                                listModel.RemoveAt(listModel.FindIndex(x => x.ESS == "GN"));
                                listModel.RemoveAt(listModel.FindIndex(x => x.ESS == "GT"));
                            }
                        }
                        //tempModel.UNTT = "getdate()";
                        listModel.Add(tempModel);
                        listEssData.RemoveRange(0, intEssLength + 2);
                        return ParseEssData(listEssData, essDataModel, ref listModel);
                    }
                    else
                    {
                        Messages.SaveLog("解析要素数据错误,数据内容:" + TransData.ConvertData(listEssData.ToArray()), ELogLayer.BusinessRule, ELogType.Error);
                        return false;
                    }
                }
                else
                {
                    Messages.SaveLog(string.Format("未找到与{0}匹配的要素", strEssCode), ELogLayer.BusinessRule, ELogType.Error);
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 解析遥测站图片报
        /// </summary>
        /// <param name="connId">客户端连接ID</param>
        /// <param name="byteData">数据</param>
        /// <param name="essDataModel">要素</param>
        /// <returns>true,false</returns>
        public static bool ParseSL651PictureReport(IntPtr connId, byte[] byteData, ref EssDataModel essDataModel)
        {
            try
            {
                //bool blnOk = true;
                int intLength = 0;//报文正文数据长度
                int serial = 0;//流水号
                string strTime1;// 发报时间
                string strAddrNo;//遥测站地址标识符
                string strAddr; //遥测站地址
                byte[] addr = new byte[5];
                byte[] byteSerial = new byte[2];
                //string strAddrType;//遥测站类型
                string strTime2; //观测时间
                byte[] byteEssData1;//图片头数据
                byte[] byteEssData2;//图片数据
                int pictureHeadLength = 28;//图片第一包包头长度
                int totalPackages = 0;
                int indexPackages = 0;

                byte[] bytePackage = new byte[3];
                Array.Copy(byteData, 14, bytePackage, 0, 3);
                Array.Copy(byteData, 3, addr, 0, 5);
                TransData.GetTotalPackageAndSerialNumber(bytePackage, ref totalPackages, ref indexPackages);
                if (totalPackages == 0 || indexPackages == 0)
                {
                    Messages.SaveLog("图片包数错误,数据:" + TransData.ConvertData(byteData), ELogLayer.UI, ELogType.Info);
                    return false;
                }

                ClientModel cm = MainForm.server.GetExtra<ClientModel>(connId);
                //Messages.SaveLog("0000000000000000000000000000");
                //ClientModel cm = MainForm.listClient.Find(t => t.ClientId == connId.ToString());
                if (cm != null)
                {
                    //Messages.SaveLog("111111111111111111111111");
                    intLength = TransData.ConvertNum(byteData[11], byteData[12]);
                    if (indexPackages == 1)//第一包数据
                    {
                        byteEssData1 = new byte[intLength];
                        Array.Copy(byteData, MainForm.Rtu_header_size, byteEssData1, 0, intLength);
                        Array.Copy(byteEssData1, 3, byteSerial, 0, 2);
                        serial = TransData.ConvertNum(byteSerial[0], byteSerial[1]);
                        byte[] time1 = new byte[6];
                        Array.Copy(byteEssData1, 5, time1, 0, 6);
                        strTime1 = TransData.DataToDateString(time1);
                        byte[] add = new byte[2];
                        Array.Copy(byteEssData1, 11, add, 0, 2);
                        strAddrNo = TransData.ConvertData(add);
                        strAddr = TransData.ConvertData(addr);
                        byte[] addrType = new byte[1];//遥测站类型
                        Array.Copy(byteEssData1, 18, addrType, 0, 1);
                        byte[] time2 = new byte[5];
                        Array.Copy(byteEssData1, 21, time2, 0, 5);
                        strTime2 = TransData.DataToDateString(time2);
                        byteEssData2 = new byte[intLength - pictureHeadLength];
                        Array.Copy(byteEssData1, pictureHeadLength, byteEssData2, 0, intLength - pictureHeadLength);
                        cm.DataModel.SubPackageStartTime = DateTime.Now;
                        cm.DataModel.ST = strAddr;
                        //strTime2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm") +":00";//测试用，正式用要注释掉
                        cm.DataModel.TT = Convert.ToDateTime(strTime2).ToString("yyyy-MM-dd HH:mm:ss.fff");
                        cm.DataModel.TYPE = "PICTURE";
                        cm.DataModel.SERIAL = serial;
                        cm.DataModel.TELTYPE = Convert.ToInt16(addrType[0]);
                        cm.DataModel.ESS = "PIC";
                        cm.DataModel.UT = Convert.ToDateTime(strTime1).ToString("yyyy-MM-dd HH:mm:ss.fff");
                        cm.DataModel.DATA = 0;
                        cm.DataModel.IsSubPackage = true;
                        cm.DataModel.TotalPackages = totalPackages;
                        cm.DataModel.CurrentPackage = indexPackages;
          
                        if (DataBusiness.SelectImageData(cm.DataModel.ST, cm.DataModel.TT, cm.DataModel.ESS, INIConfig.GetDBConnectionString()) > 0)
                        {
                            return false;
                        }
                        cm.DataModel.DataPackages.Clear();
                        cm.DataModel.DataPackages.Add(indexPackages, byteEssData2);
                        essDataModel = cm.DataModel;

                    }
                    else
                    {
                        byteEssData2 = new byte[intLength - 3];
                        Array.Copy(byteData, MainForm.Rtu_multi_header_size, byteEssData2, 0, intLength - 3);
                        cm.DataModel.IsSubPackage = true;
                        cm.DataModel.TotalPackages = totalPackages;
                        cm.DataModel.CurrentPackage = indexPackages;
                        essDataModel.TT = cm.DataModel.TT;
                        essDataModel.ST = cm.DataModel.ST;
                        essDataModel.TotalPackages = totalPackages;
                        essDataModel.CurrentPackage = indexPackages;
                        if (!cm.DataModel.DataPackages.ContainsKey(indexPackages))
                        {
                            cm.DataModel.DataPackages.Add(indexPackages, byteEssData2);
                        }
                        else
                        {
                            cm.DataModel.DataPackages[indexPackages] = byteEssData2;
                        }
                        if (totalPackages == indexPackages && totalPackages == cm.DataModel.DataPackages.Count)//最后一包
                        {
                            //20240125
                            //byte[] byteDataSub = new byte[12];
                            //Array.Copy(byteData, 0, byteDataSub, 0, 12);
                            //MainForm.ImageResponse(connId, addr, byteDataSub, bytePackage, byteSerial);
                            //20240125
                            if (!DataBusiness.CheckData(cm.DataModel.ST, cm.DataModel.TT, cm.DataModel.TYPE, cm.DataModel.SERIAL))
                            {
                                string strPath = INIConfig.ImagePath + "\\" + DateTime.Now.Year + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + cm.DataModel.ST + "\\" + cm.DataModel.ST + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
                                List<byte> listTemp = new List<byte>();
                                foreach (var s in cm.DataModel.DataPackages)
                                {
                                    listTemp.AddRange(s.Value);
                                }
                                if (CreateImageFile(strPath, listTemp.ToArray())){
                                    cm.DataModel.DataPackages.Clear();
                                        cm.DataModel.SubPackageStartTime = null;
                                        cm.DataModel.IsSubPackage = false;
                                        cm.DataModel.TotalPackages = 0;
                                        cm.DataModel.CurrentPackage = 0;
                                        cm.DataModel.STT = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                                        cm.DataModel.UNTT = cm.DataModel.STT;
                                        cm.DataModel.SDATA = strPath;
                                        int i = MainForm.TransDeviceInfo.Select("ST='" + cm.DataModel.ST + "'").Length;
                                        DataBusiness.CreateHisDataTable(cm.DataModel.ST, INIConfig.GetDBConnectionString());
                                    //读库
                                    if (i >= 1) {
                                                DataBusiness.CreateHisDataTable(cm.DataModel.ST, INIConfig.GetRDBConnectionString());
                                            }

                                            DataBusiness.InserHisData(cm.DataModel, INIConfig.GetDBConnectionString());
                                            //读库
                                            if (i >= 1)
                                            {
                                                DataBusiness.InserHisData(cm.DataModel, INIConfig.GetRDBConnectionString());
                                            }
                                } else {
                                                //essDataModel.Message = string.Format("遥测站{0}[{1}]图片报保存失败", cm.DataModel.ST, cm.DataModel.TT);
                                                Messages.SaveLog(string.Format("遥测站{0}[{1}]图片报保存失败", cm.DataModel.ST, cm.DataModel.TT), ELogLayer.UI, ELogType.Info);
                                                //blnOk = false;
                                }
                            } else
                            {
                                //essDataModel.Message = string.Format("遥测站{0}[{1}]图片报数据重复", cm.DataModel.ST, cm.DataModel.TT);
                                Messages.SaveLog(string.Format("遥测站{0}[{1}]图片报数据重复", cm.DataModel.ST, cm.DataModel.TT), ELogLayer.UI, ELogType.Info);
                                //blnOk = true;
                            }
                            cm.DataModel = new EssDataModel();
                            //MainForm.listClient.Remove(cm);
                            //Thread.Sleep(10);
                        }
                    }
                }
                else
                {
                    Messages.SaveLog("查找不到对应客户端连接", ELogLayer.UI, ELogType.Info);
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                Messages.SaveLog(string.Format("解析遥测站图片报异常:{0}", ex.Message), ELogLayer.UI, ELogType.Info);
                return false;
            }
        }
     
       
    /// <summary>
    /// 生成图片文件
    /// </summary>
    /// <param name="strPath">路径</param>
    /// <param name="byteImage">文件字节</param>
    /// <returns></returns>
    public static bool CreateImageFile(string strPath, byte[] byteImage)
        {
            try
            {
                string strValue = Path.GetDirectoryName(strPath);
                if (!Directory.Exists(strValue))
                {
                    Directory.CreateDirectory(strValue);
                }

                FileStream fs = new FileStream(strPath, FileMode.Create, FileAccess.ReadWrite);
                fs.Write(byteImage, 0, byteImage.Length);
                fs.Flush();
                fs.Close();
                return true;
            }
            catch(Exception ex)
            {
                Messages.SaveLog(string.Format("遥测站图片路径{0}保存失败:{1}", strPath, ex.Message), ELogLayer.UI, ELogType.Info);
                return false;
            }
        }

        /// <summary>
        /// 添加实时数据和报警信息
        /// </summary>
        /// <param name="strStationNo">站点编号</param>
        /// <param name="listModel">要素实时数据model</param>
        //public static void AddEssData(string strStationNo, List<EssDataModel> listModel)
        //{
        //    string strEss = DataBusiness.GetStationEssDataToString(listModel);
        //    string strAlarm = string.Empty;
        //    List<EssDataModel> essModel = listModel.Where<EssDataModel>(x => x.ESS == "ZT").ToList<EssDataModel>();
        //    if (essModel.Count > 0)
        //    {
        //        strAlarm = DataBusiness.GetAlarmToString(essModel[0].DATA.ToString());
        //    }

        //    DataRow[] dr = MainForm.dtDeviceInfo.Select(string.Format("StationNo='{0}'", strStationNo));
        //    if (dr.Length > 0)
        //    {
        //        dr[0][1] = strEss;
        //        dr[0][2] = strAlarm;
        //        MainForm.dtDeviceInfo.AcceptChanges();
        //    }
        //    else
        //    {
        //        MainForm.dtDeviceInfo.Rows.Add(strStationNo, strEss, strAlarm);
        //    }
        //}
    }
}
